package Volume2.ch1;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 2.流的创建
 * @Auther jacob
 * @Date 2020/8/9 17:03
 */
public class CreatingStreams {

    public static<T> void show(String title, Stream<T> stream){
        final int SIZE = 10;
        List<T> firstElements = stream
                .limit(SIZE + 1)
                .collect(Collectors.toList());
        System.out.print(title + ": ");

        for (int i = 0; i < firstElements.size(); i++) {
            if (i > 0){
                System.out.print(", ");
            }
            if (i < SIZE){
                System.out.print(firstElements.get(i));
            }
            else {
                System.out.print("...");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("src/Volume2/ch1/words.txt");
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

        // 通过Stream.of将数组转化为流
        Stream<String> words = Stream.of(contents.split("\n"));
        show("words", words);

        // 通过Stream.empty()创建流
        Stream<String> silence = Stream.empty();
        show("silence", silence);

        // 通过Stream.generate创建常量值的流
        Stream<String> echos = Stream.generate(() -> "Echo");
        show("echos", echos);

        // 通过Stream.generate创建随机数的流
        Stream<Double> randoms = Stream.generate(Math::random);
        show("randoms", randoms);

        Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.TEN));
        show("integers", integers);
    }
}
